import cv2
import numpy as np

class ImageProcessor:
    def __init__(self):
        pass
    
    def create_grid(self, image, grid_size):
        """
        将图像按指定大小划分网格并绘制网格线
        
        Args:
            image: 输入图像 (numpy数组，RGB格式)
            grid_size: 网格大小 (像素)
            
        Returns:
            带有网格线的图像
        """
        # 创建图像副本
        grid_image = image.copy()
        h, w = image.shape[:2]
        
        # 绘制垂直线
        for x in range(0, w, grid_size):
            cv2.line(grid_image, (x, 0), (x, h), (0, 0, 0), 1)
        
        # 绘制水平线
        for y in range(0, h, grid_size):
            cv2.line(grid_image, (0, y), (w, y), (0, 0, 0), 1)
        
        return grid_image
    
    def split_into_grids(self, image, grid_size):
        """
        将图像分割成网格单元
        
        Args:
            image: 输入图像
            grid_size: 网格大小
            
        Returns:
            网格单元列表，每个元素为(行索引, 列索引, 网格图像)
        """
        h, w = image.shape[:2]
        grids = []
        
        for y in range(0, h, grid_size):
            for x in range(0, w, grid_size):
                # 确保网格不超出图像边界
                end_y = min(y + grid_size, h)
                end_x = min(x + grid_size, w)
                
                # 提取网格
                grid = image[y:end_y, x:end_x]
                grids.append((y // grid_size, x // grid_size, grid))
        
        return grids
    
    def resize_image(self, image, max_size=800):
        """
        调整图像大小，保持纵横比
        
        Args:
            image: 输入图像
            max_size: 最大尺寸
            
        Returns:
            调整后的图像
        """
        h, w = image.shape[:2]
        
        # 计算缩放比例
        scale = min(max_size / w, max_size / h)
        
        # 如果图像已经小于最大尺寸，则不调整
        if scale >= 1:
            return image
        
        # 调整图像大小
        new_w = int(w * scale)
        new_h = int(h * scale)
        resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
        
        return resized
    
    def apply_grid_overlay(self, image, overlay, grid_size, alpha=0.7):
        """
        将网格叠加层应用到原始图像上
        
        Args:
            image: 原始图像
            overlay: 叠加层图像 (与原始图像相同大小)
            grid_size: 网格大小
            alpha: 透明度 (0-1)
            
        Returns:
            叠加后的图像
        """
        result = image.copy()
        h, w = image.shape[:2]
        
        # 确保叠加层与原始图像大小相同
        if overlay.shape[:2] != (h, w):
            overlay = cv2.resize(overlay, (w, h))
        
        # 应用叠加
        cv2.addWeighted(overlay, alpha, result, 1 - alpha, 0, result)
        
        # 重新绘制网格线以确保可见性
        for x in range(0, w, grid_size):
            cv2.line(result, (x, 0), (x, h), (0, 0, 0), 1)
        
        for y in range(0, h, grid_size):
            cv2.line(result, (0, y), (w, y), (0, 0, 0), 1)
        
        return result